package fic.storefinder.server.uploadservice;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FilenameUtils;

import fic.storefinder.shared.utils.Constants;

@SuppressWarnings("serial")
public class ImageUploadServlet extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		super.doGet(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

		ServletFileUpload upload = new ServletFileUpload();

		try {
			FileItemIterator iter = upload.getItemIterator(req);

			while (iter.hasNext()) {
				FileItemStream item = iter.next();

				String name = item.getFieldName();
				try {
					Integer.parseInt(name);
				} catch (Exception e) {
					continue;
				}
				InputStream stream = item.openStream();

				File f = new File(Constants.CONFIG_UPLOAD_DIR_PATH + "img_" + System.currentTimeMillis() + ".jpg");
				if (!f.exists()) {
					f.createNewFile();
				}
				//ByteArrayOutputStream out = new ByteArrayOutputStream();
				FileOutputStream fos = new FileOutputStream(f);
				int len;
				byte[] buffer = new byte[8192];
				while ((len = stream.read(buffer, 0, buffer.length)) != -1) {
					fos.write(buffer, 0, len);
				}
				fos.close();
				
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

}
